<template>
  <div class="smart-qa-container">
    <!-- 左侧历史记录 -->
    <div class="history-sidebar">
      <div class="history-header">
        <h3>历史对话</h3>
        <button class="new-chat-btn" @click="startNewChat">
          <i class="plus-icon"></i>
          新对话
        </button>
      </div>
      <div class="history-list">
        <div 
          v-for="chat in chatHistory" 
          :key="chat.id"
          class="history-item"
          :class="{ active: currentChatId === chat.id }"
          @click="selectChat(chat.id)"
        >
          <div class="chat-title">{{ chat.title }}</div>
          <div class="chat-time">{{ formatTime(chat.lastTime) }}</div>
        </div>
        <div v-if="chatHistory.length === 0" class="empty-history">
          暂无历史对话
        </div>
      </div>
    </div>

    <!-- 右侧对话区域 -->
    <div class="chat-area">
      <div class="chat-header">
        <h2>智能问答助手</h2>
        <p class="chat-subtitle">我是您的职场智能助手，可以为您解答求职、面试、职业规划等问题</p>
      </div>

      <div class="chat-messages" ref="messagesContainer">
        <div v-if="currentMessages.length === 0" class="welcome-message">
          <div class="welcome-content">
            <div class="welcome-icon">🤖</div>
            <h3>欢迎使用智能问答</h3>
            <p>您可以问我关于以下内容的问题：</p>
            <div class="suggestion-tags">
              <span class="tag" @click="askSuggestion('如何写一份优秀的简历？')">简历撰写</span>
              <span class="tag" @click="askSuggestion('面试时需要注意什么？')">面试技巧</span>
              <span class="tag" @click="askSuggestion('如何进行职业规划？')">职业规划</span>
              <span class="tag" @click="askSuggestion('如何提升职场竞争力？')">能力提升</span>
            </div>
          </div>
        </div>

        <div 
          v-for="message in currentMessages" 
          :key="message.id"
          class="message-item"
          :class="{ 'user-message': message.type === 'user', 'ai-message': message.type === 'ai' }"
        >
          <div class="message-avatar">
            <div v-if="message.type === 'user'" class="user-avatar">👤</div>
            <div v-else class="ai-avatar">🤖</div>
          </div>
          <div class="message-content">
            <div class="message-text" v-if="message.type === 'user'">{{ message.content }}</div>
            <div class="message-text" v-else v-html="renderMarkdown(message.content)"></div>
            <div class="message-time">{{ formatTime(message.time) }}</div>
          </div>
        </div>

        <div v-if="isTyping" class="message-item ai-message typing">
          <div class="message-avatar">
            <div class="ai-avatar">🤖</div>
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-input-area">
        <div class="input-container">
          <textarea
            v-model="inputMessage"
            ref="messageInput"
            placeholder="请输入您的问题..."
            class="message-input"
            rows="1"
            @keydown.enter.prevent="handleEnter"
            @input="adjustTextareaHeight"
          ></textarea>
          <button 
            class="send-btn" 
            :disabled="!inputMessage.trim() || isTyping"
            @click="sendMessage"
          >
            <i class="send-icon"></i>
          </button>
        </div>
        <div class="input-tips">
          按 Enter 发送，Shift + Enter 换行
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import MarkdownIt from 'markdown-it'
import DOMPurify from 'dompurify'

// 响应式数据
const inputMessage = ref('')
const isTyping = ref(false)
const currentChatId = ref(null)
const messagesContainer = ref(null)
const messageInput = ref(null)
// Markdown 渲染器
const md = new MarkdownIt({ breaks: true, linkify: true, html: false })
const renderMarkdown = (text) => {
  try {
    // 压缩多余空行，避免渲染后留白过大
    const compact = String(text || '').replace(/\n{3,}/g, '\n\n').trim()
    const rendered = md.render(compact)
    return DOMPurify.sanitize(rendered)
  } catch (e) {
    return String(text || '')
  }
}

// 聊天历史
const chatHistory = reactive([
  {
    id: 1,
    title: '简历优化建议',
    lastTime: new Date(Date.now() - 1000 * 60 * 30), // 30分钟前
    messages: [
      {
        id: 1,
        type: 'user',
        content: '如何写一份优秀的简历？',
        time: new Date(Date.now() - 1000 * 60 * 30)
      },
      {
        id: 2,
        type: 'ai',
        content: '写一份优秀简历的关键要点包括：\n\n1. **突出核心信息**：姓名、联系方式、求职意向要清晰明确\n2. **量化工作成果**：用具体数字展示你的业绩和贡献\n3. **技能匹配**：针对目标岗位突出相关技能和经验\n4. **简洁明了**：控制在1-2页，避免冗余信息\n5. **专业格式**：使用清晰的排版和专业的字体\n\n需要我为您详细解释某个方面吗？',
        time: new Date(Date.now() - 1000 * 60 * 29)
      }
    ]
  },
  {
    id: 2,
    title: '面试准备指南',
    lastTime: new Date(Date.now() - 1000 * 60 * 60 * 2), // 2小时前
    messages: [
      {
        id: 1,
        type: 'user',
        content: '面试时需要注意什么？',
        time: new Date(Date.now() - 1000 * 60 * 60 * 2)
      },
      {
        id: 2,
        type: 'ai',
        content: '面试成功的关键要素：\n\n**面试前准备**\n• 深入了解公司背景和职位要求\n• 准备常见问题的回答\n• 整理相关作品和证书\n\n**面试中表现**\n• 保持自信和专业的形象\n• 主动沟通，展示你的热情\n• 准备有质量的问题询问面试官\n\n**注意事项**\n• 准时到达，最好提前10-15分钟\n• 关闭手机或调至静音\n• 保持良好的身体语言和眼神交流',
        time: new Date(Date.now() - 1000 * 60 * 60 * 2 + 1000 * 30)
      }
    ]
  }
])

// 当前对话消息
const currentMessages = ref([])

// 方法
const formatTime = (date) => {
  const now = new Date()
  const diff = now - date
  
  if (diff < 1000 * 60) return '刚刚'
  if (diff < 1000 * 60 * 60) return `${Math.floor(diff / (1000 * 60))}分钟前`
  if (diff < 1000 * 60 * 60 * 24) return `${Math.floor(diff / (1000 * 60 * 60))}小时前`
  return date.toLocaleDateString()
}

const selectChat = (chatId) => {
  currentChatId.value = chatId
  const chat = chatHistory.find(c => c.id === chatId)
  if (chat) {
    currentMessages.value = [...chat.messages]
    nextTick(() => {
      scrollToBottom()
    })
  }
}

const startNewChat = () => {
  currentChatId.value = null
  currentMessages.value = []
  inputMessage.value = ''
}

const askSuggestion = (question) => {
  inputMessage.value = question
  sendMessage()
}

const handleEnter = (event) => {
  if (event.shiftKey) {
    return // 允许换行
  }
  sendMessage()
}

const adjustTextareaHeight = () => {
  const textarea = messageInput.value
  if (textarea) {
    textarea.style.height = 'auto'
    textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'
  }
}

// 调用后端单轮问答接口
const callQA1 = async (question) => {
  let userid =  localStorage.getItem("userid")
  let token =  localStorage.getItem("token")

  const resp = await fetch('http://localhost:8000/qa/qa1/', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ "question": question, "userid": userid })
  })
  const data = await resp.json().catch(() => ({}))
  if (!resp.ok) throw new Error('请求失败')
  if (data?.code === 1) return data?.data?.answer || ''
  throw new Error(data?.message || '请求失败')
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isTyping.value) return

  const userMessage = {
    id: Date.now(),
    type: 'user',
    content: inputMessage.value.trim(),
    time: new Date()
  }

  // 如果是新对话，创建新的聊天记录
  if (!currentChatId.value) {
    const newChat = {
      id: Date.now(),
      title: userMessage.content.slice(0, 20) + (userMessage.content.length > 20 ? '...' : ''),
      lastTime: new Date(),
      messages: []
    }
    chatHistory.unshift(newChat)
    currentChatId.value = newChat.id
    currentMessages.value = []
  }

  currentMessages.value.push(userMessage)
  inputMessage.value = ''
  
  nextTick(() => {
    adjustTextareaHeight()
    scrollToBottom()
  })

  // 显示输入状态
  isTyping.value = true

  try {
    const aiResponse = await callQA1(userMessage.content)
    const aiMessage = {
      id: Date.now() + 1,
      type: 'ai',
      content: aiResponse || '抱歉，未获取到答案',
      time: new Date()
    }
    currentMessages.value.push(aiMessage)
  } catch (e) {
    const aiMessage = {
      id: Date.now() + 1,
      type: 'ai',
      content: '获取回答失败，请稍后再试',
      time: new Date()
    }
    currentMessages.value.push(aiMessage)
  } finally {
    isTyping.value = false
    // 更新聊天历史
    const currentChat = chatHistory.find(c => c.id === currentChatId.value)
    if (currentChat) {
      currentChat.messages = [...currentMessages.value]
      currentChat.lastTime = new Date()
    }
    nextTick(() => {
      scrollToBottom()
    })
  }
}

const getAIResponse = (question) => {
  const responses = {
    '简历': '关于简历优化，我建议您：\n\n1. **突出重点**：将最相关的经验和技能放在显眼位置\n2. **量化成果**：用数字和百分比展示您的成就\n3. **关键词优化**：包含招聘信息中的关键技能词汇\n4. **格式清晰**：使用清晰的标题和条理化的布局\n\n需要我帮您分析具体的简历内容吗？',
    
    '面试': '面试成功的关键在于充分准备：\n\n**技术准备**\n• 复习与岗位相关的专业知识\n• 准备项目经验的详细介绍\n• 了解公司的业务和文化\n\n**心理准备**\n• 保持自信和积极的心态\n• 准备应对压力面试的策略\n• 练习清晰表达自己的想法\n\n您想了解哪种类型面试的具体技巧？',
    
    '职业规划': '制定职业规划需要考虑以下几个方面：\n\n1. **自我评估**：了解自己的兴趣、能力和价值观\n2. **市场分析**：研究行业发展趋势和机会\n3. **目标设定**：制定短期、中期和长期职业目标\n4. **技能发展**：识别需要提升的核心技能\n5. **行动计划**：制定具体的实施步骤和时间表\n\n您目前处于职业发展的哪个阶段？',
    
    '薪资': '关于薪资谈判的建议：\n\n**准备阶段**\n• 调研行业薪资水平和市场行情\n• 评估自己的价值和贡献\n• 准备具体的成就案例\n\n**谈判技巧**\n• 以数据和事实为基础\n• 展示您能为公司创造的价值\n• 考虑整体薪酬包，不只是基本工资\n\n您想了解如何在面试中合适地提及薪资期望吗？'
  }
  
  // 简单的关键词匹配
  for (const [keyword, response] of Object.entries(responses)) {
    if (question.includes(keyword)) {
      return response
    }
  }
  
  // 默认回复
  return '感谢您的提问！作为您的职场智能助手，我可以帮您解答关于求职、面试、职业规划、技能提升等方面的问题。\n\n请告诉我您具体想了解什么，我会为您提供详细的建议和指导。\n\n您也可以尝试问我：\n• "如何准备技术面试？"\n• "怎样提升领导力？"\n• "如何转行到新的行业？"\n• "远程工作有什么技巧？"'
}

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 组件挂载时的初始化
onMounted(() => {
  // 默认选择第一个对话
  if (chatHistory.length > 0) {
    selectChat(chatHistory[0].id)
  }
})
</script>

<style scoped>
.smart-qa-container {
  display: flex;
  height: calc(100vh - 49px);
  margin-top: 49px;
  background: #f5f7fa;
}

/* 左侧历史记录 */
.history-sidebar {
  width: 280px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.history-header {
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.history-header h3 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.new-chat-btn {
  width: 100%;
  padding: 10px;
  background: #00BEBD;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 14px;
  transition: background-color 0.3s;
}

.new-chat-btn:hover {
  background: #009a9a;
}

.plus-icon::before {
  content: '+';
  font-size: 16px;
  font-weight: bold;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.history-item {
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
  border: 1px solid transparent;
}

.history-item:hover {
  background: #f5f7fa;
}

.history-item.active {
  background: #e6f9f9;
  border-color: #00BEBD;
}

.chat-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-time {
  font-size: 12px;
  color: #909399;
}

.empty-history {
  text-align: center;
  color: #909399;
  font-size: 14px;
  padding: 40px 20px;
}

/* 右侧对话区域 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.chat-header {
  padding: 20px 30px;
  border-bottom: 1px solid #e4e7ed;
  background: #fff;
}

.chat-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.chat-subtitle {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px 30px;
  background: #fafbfc;
}

.welcome-message {
  text-align: center;
  padding: 60px 20px;
}

.welcome-content {
  max-width: 500px;
  margin: 0 auto;
}

.welcome-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.welcome-content h3 {
  color: #303133;
  font-size: 24px;
  margin-bottom: 10px;
}

.welcome-content p {
  color: #606266;
  font-size: 16px;
  margin-bottom: 30px;
}

.suggestion-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
}

.tag {
  padding: 8px 16px;
  background: #e6f9f9;
  color: #00BEBD;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #00BEBD;
}

.tag:hover {
  background: #00BEBD;
  color: white;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin: 0 15px;
  flex-shrink: 0;
}

.user-avatar {
  background: #00BEBD;
  color: white;
}

.ai-avatar {
  background: #f0f2f5;
  color: #606266;
}

.message-content {
  max-width: 70%;
  min-width: 100px;
}

.user-message .message-content {
  text-align: right;
}

.message-text {
  background: #fff;
  padding: 12px 16px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.5;
  color: #303133;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  white-space: pre-wrap;
}

/* 压缩 Markdown 元素的上下间距，让排版更紧凑 */
.ai-message .message-text h1,
.ai-message .message-text h2,
.ai-message .message-text h3,
.ai-message .message-text h4,
.ai-message .message-text h5,
.ai-message .message-text h6 { margin: 8px 0 6px; }
.ai-message .message-text p { margin: 6px 0; }
.ai-message .message-text ul,
.ai-message .message-text ol { margin: 6px 0 6px 18px; }
.ai-message .message-text li { margin: 2px 0; }
.ai-message .message-text hr { margin: 10px 0; }

.user-message .message-text {
  background: #00BEBD;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.user-message .message-time {
  text-align: right;
}

.typing {
  opacity: 0.8;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 12px 16px;
  background: #f0f2f5;
  border-radius: 12px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #909399;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    opacity: 0.3;
    transform: scale(0.8);
  }
  40% {
    opacity: 1;
    transform: scale(1);
  }
}

/* 输入区域 */
.chat-input-area {
  padding: 20px 30px;
  border-top: 1px solid #e4e7ed;
  background: #fff;
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 15px;
  margin-bottom: 8px;
}

.message-input {
  flex: 1;
  min-height: 44px;
  max-height: 120px;
  padding: 12px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 22px;
  font-size: 14px;
  line-height: 1.4;
  resize: none;
  outline: none;
  font-family: inherit;
  transition: border-color 0.3s;
}

.message-input:focus {
  border-color: #00BEBD;
}

.send-btn {
  width: 44px;
  height: 44px;
  background: #00BEBD;
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s;
  flex-shrink: 0;
}

.send-btn:hover:not(:disabled) {
  background: #009a9a;
}

.send-btn:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
}

.send-icon::before {
  content: '➤';
  font-size: 16px;
}

.input-tips {
  font-size: 12px;
  color: #909399;
  text-align: center;
}

/* 滚动条样式 */
.history-list::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.history-list::-webkit-scrollbar-track,
.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-thumb,
.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-thumb:hover,
.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .smart-qa-container {
    flex-direction: column;
  }
  
  .history-sidebar {
    width: 100%;
    height: 200px;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .chat-messages {
    padding: 15px 20px;
  }
  
  .chat-input-area {
    padding: 15px 20px;
  }
}
</style>